package com.example.smartcity_poverty.ui.Home

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.example.smartcity_poverty.App
import com.example.smartcity_poverty.App.Companion.url
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.util.Util
import com.example.smartcity_poverty.logic.util.Util.glide
import com.example.smartcity_poverty.logic.util.Util.show
import com.example.smartcity_poverty.ui.AllService.TakeOutTr.TakeOutHomeActivity
import com.example.smartcity_poverty.ui.ShowNewsActivity
import com.example.smartcity_poverty.ui.Home.Seek.SeekActivity
import com.example.smartcity_poverty.ui.Home.adapter.HotAdapter
import com.example.smartcity_poverty.ui.Home.adapter.MoreAdapter
import com.example.smartcity_poverty.ui.Home.fragment.NewsFragment
import com.example.smartcity_poverty.ui.Home.fragment.NewsFragment.Companion.newsId
import com.google.android.material.tabs.TabLayout
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.coroutines.Dispatchers

/**
 * 底部导航栏 - app主页
 */
class HomeFragment : Fragment(), View.OnClickListener {

    private val TAG = this.javaClass.simpleName.toString()

    private val viewModel by lazy {
        ViewModelProviders.of(this)[HomeViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }


    /**
     * kotlin提供的插件需要在已经创建好的布局上使用
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 设置动画
        setAnimation()

//        // 点击进入Java版智慧城市
//        startJavaSmartCity()
//        // 点击进入外卖订餐模块
//        startTakeOut()

        // 设置轮播图
        setBanner()
        // 全部服务
        setMore()
        // 热门主题
        setHot()
        // 新闻专栏
        tabNews()
        // 搜索
        seek()
    }


//    /**
//     * create DATE 2023-11-5
//     * 点击进入Java版智慧城市
//     */
//    private fun startJavaSmartCity() = tvJava.setOnClickListener {
//        // 暂时不开发
//        "开发中...".show()
//        // startActivity(Intent(context, JavaSmartCityActivity::class.java))
//    }
//
//    /**
//     * 点击进入外卖订餐模块
//     */
//    private fun startTakeOut()  = tvTakeOut.setOnClickListener {
//        Util.startActivityUtils(App.context, TakeOutHomeActivity())
//    }


    override fun onClick(view: View?) = when (view?.id) {
        else -> {
            throw Exception("$TAG onClick: 出现错误")
        }
    }


    /**
     * 设置动画
     */
    private fun setAnimation() {
        // 搜索框设置动画
        homeSeek.animation = App.getAnimationTopAndBottom()

        // 轮播图设置动画
        homeBanner.animation = App.getAnimationLeftAndEnd()

        // 更多服务 设置动画
        HomeAnimationCardMore.animation = App.getAnimationEndAndStart()
    }


    /**
     * 首页新闻 模糊查询
     */
    private fun seek() {
        homeSeek.setOnEditorActionListener { _, i, _ ->
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                if (homeSeek.text.toString().isEmpty()) {
                    "您还没有输入内容！".show()
                } else {
                    startActivity(Intent(context, SeekActivity::class.java).apply {
                        putExtra("content", homeSeek.text.toString())
                    })
                    // 清空输入框
                    homeSeek.setText("")
                }
            }
            false
        }
    }


    /**
     * 设置轮播图
     */
    private fun setBanner() {
        val arr = ArrayList<String>()

        viewModel.setBanner(mapOf("pageNum" to 1, "pageSize" to 8, "type" to 2))
        viewModel.bannerLiveData.observe(this, Observer { resources ->
            val body = resources.getOrNull()
            if (body != null) {
                viewModel.bannerList.clear()
                viewModel.bannerList.addAll(body.rows!!)
            } else "加载轮播图失败！".show()

            for (i in viewModel.bannerList) {
                arr.add(url + i.advImg)
            }

            homeBanner.apply {
                // 配置轮播图适配器
                this.adapter = object : BannerImageAdapter<String>(arr) {
                    override fun onBindView(p0: BannerImageHolder?, p1: String?, p2: Int, p3: Int) {
                        glide(p1.toString(), p0?.imageView!!)
                    }
                }

                this.addBannerLifecycleObserver(this@HomeFragment).indicator =
                    CircleIndicator(context)
                // 设置轮播图圆角
                this.setBannerRound(25f)
                // 设置轮播图样式
                // 设置轮播图点击事件
                this.setOnBannerListener { _, i ->
                    when (i) {
                        0 -> startActivity(
                            Intent(
                                context,
                                ShowNewsActivity::class.java
                            ).putExtra("id", "25")
                        )
                        1 -> startActivity(
                            Intent(
                                context,
                                ShowNewsActivity::class.java
                            ).putExtra("id", "26")
                        )
                        2 -> startActivity(
                            Intent(
                                context,
                                ShowNewsActivity::class.java
                            ).putExtra("id", "27")
                        )
                    }
                }
            }
        })
    }


    /**
     * 全部服务
     */
    private fun setMore() {
        val arrMore = ArrayList<HomeMoreEntity>()


        // TODO 不使用ViewModel
/*        viewModel.moreLiveData.observe(this, Observer { resources ->
            val body = resources.getOrNull()
            if (body != null) {
                viewModel.moreList.clear()
                viewModel.moreList.addAll(body.rows!!)
            }

            for (i in viewModel.moreList){
                arrMore.add(HomeMoreEntity(i.sort, url + i.imgUrl, 0, i.serviceName.toString()))
            }

            homeMoreRecycler.apply {
                this.layoutManager = GridLayoutManager(context, 5)
                this.adapter = MoreAdapter(
                    true,
                    10,
                    this@HomeFragment,
                    arrMore,
                    R.layout.re_item_more
                )
            }
        })*/

        // TODO 使用协程来发起网络请求获取数据
        // 开启协程
        coroutine(Dispatchers.Main) {
            // 获取更多服务器
            api.getMore().apply {
                // 判断是否获取数据成功
                if (this.code == 200) {
                    // 成功的话将数据取出来存储到数组里
                    for (i in this.rows!!) {

                        arrMore.add(
                            HomeMoreEntity(
                                i.sort,
                                url + i.imgUrl,
                                0,
                                i.serviceName.toString()
                            )
                        )

                        // 遍历取完数据后配置适配器
                        homeMoreRecycler.apply {
                            this.layoutManager = GridLayoutManager(context, 5)
                            this.adapter = MoreAdapter(
                                true,
                                10,
                                this@HomeFragment,
                                arrMore,
                                R.layout.re_item_more
                            )
                            this.adapter?.notifyItemChanged(arrMore.size)
                        }
                    }


                }
            }
        }
    }

    class HomeMoreEntity(
        val id: Int,
        val moreUrl: String,
        val moreUrlInt: Int,
        val moreTitle: String
    )

    /**
     * 热门主题
     */
    private fun setHot() {
        viewModel.newsHotLiveData.observe(this, Observer { resources ->
            val body = resources.getOrNull()
            if (body != null) {
                viewModel.newsHotList.clear()
                viewModel.newsHotList.addAll(body.rows!!)
                homeHot.apply {
                    this.layoutManager = LinearLayoutManager(context).apply {
                        this.orientation = LinearLayoutManager.HORIZONTAL
                    }
                    this.adapter = HotAdapter(viewModel.newsHotList, R.layout.re_item_hot)
                }
            }
        })
    }


    /**
     * 新闻专栏
     */
    private fun tabNews() {
        val arr = listOf<String>(
            "今日要闻",
            "专题聚焦",
            "政策解读",
            "经济发展",
            "文化旅游",
            "科技创新"
        )

        for (i in arr) {
            homeTabLayout.addTab(homeTabLayout.newTab().setText(i))
        }

        // VewPager
        homeViewPager2.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = 6

            override fun createFragment(position: Int): Fragment = when (position) {
                0 -> NewsFragment()
                1 -> NewsFragment()
                2 -> NewsFragment()
                3 -> NewsFragment()
                4 -> NewsFragment()
                else -> NewsFragment()
            }

            override fun getItemId(position: Int): Long {
                newsId = when (position) {
                    0 -> 9
                    1 -> 17
                    2 -> 19
                    3 -> 20
                    4 -> 21
                    else -> 22
                }
                return super.getItemId(position)
            }
        }

        // 监听ViewPager的滑动切换TabLayout标签
        homeViewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                homeTabLayout.getTabAt(position)?.select()
            }
        })

        // 监听TabLayout点击，切换ViewPager2页面
        homeTabLayout.tabMode = TabLayout.MODE_SCROLLABLE
        homeTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                homeViewPager2.currentItem = tab?.position!!
            }

        })
    }
}